/*
 * Author: PangWei
 */ 
(function($el, UA){
  var Flexible = {
    device : {
      newApps : UA.match(/NewsApp/gi),
      wx      : UA.match(/micromessenger/gi),
      iPad    : UA.match(/ipad/gi),
      iPhone  : UA.match(/iphone/gi),
      ios     : UA.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
      android : UA.match(/android/gi),
      pc      : UA.match(/Windows/gi) || UA.match(/Macintosh/gi),
      retina  : devicePixelRatio>=2 && $el.getBoundingClientRect().width>320,
      dev     : /^(dev|localhost|test|[1-9][0-9]+)/.test(location.hostname)
    },
    init: function(){
      var _ = this;

      _.refreshRem();     // 根字体
      _.addDocClassName();// 环境类名
      _.wxHandle();       // 阻止微信环境下字体大小的调整

      var timer = null;
      window.addEventListener('resize', function(){
        clearTimeout(timer);
        timer = setTimeout(_.refreshRem(), 300);
      }, false);
    },
    refreshRem: function(){
      var docEl = document.documentElement,
          resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
          recalc = function() {
              var clientWidth = docEl.clientWidth;
              if (!clientWidth) return;
              if (clientWidth >= 640) {
                  //docEl.style.fontSize = '100px';
                docEl.style.fontSize = 100 * (clientWidth / 1024) + 'px';
              } else {
                  //此时1rem=100px
                docEl.style.fontSize = 100 * (clientWidth / 640) + 'px';
              }
          };
      if (!document.addEventListener) return;
      window.addEventListener(resizeEvt, recalc, false);
      document.addEventListener('DOMContentLoaded', recalc, false);
    },
    addDocClassName: function(){
      var _=this, docClass=_.device.pc ? 'pc-style' : 'm-style';

      // 平台区分
      if( _.device.ios ){
        docClass += ' ios-style dpr-'+devicePixelRatio;
      }else if( _.device.android ){
        docClass += ' android-style';
      }

      // 环境区分
      if(_.device.newApps) docClass += ' app-style';
      if(_.device.iPad) docClass += ' ipad-style';
      if(_.device.wx) docClass += ' wx-style';

      docClass = !$el.className?docClass:' '+docClass;
      $el.className += docClass;
    },
    wxHandle: function(){
      if(!this.device.wx) return;

      var wxJSBridge = typeof WeixinJSBridge == 'object' && typeof WeixinJSBridge.invoke == 'function';
        wxJSBridge ? handleFontSize() : document.addEventListener('WeixinJSBridgeReady', handleFontSize, false);

      function handleFontSize(){
        WeixinJSBridge.invoke('setFontSizeCallback', {'fontSize': 0});
        WeixinJSBridge.on('menu:setfont', function(){
          WeixinJSBridge.invoke('setFontSizeCallback', {'fontSize': 0});
        });
      };
    }
  }

  Flexible.init();
  window.device = Flexible.device;

})(document.documentElement, navigator.appVersion);